/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package logmatcher.buffers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import logmatcher.InputFilter;
import logmatcher.LogEventBuffer;
import logmatcher.LogEventListener;

import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.buffer.UnboundedFifoBuffer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 *  Implementation of LogBuffer. Enables using message listeners with or without filtering mechanism. If input
 *  filters are  installed then message listener receive the message only when one of the filters accept the message.
 *  Otherwise, if there are  no filters then message listener receive the message at once. All listeners are checked
 *  while handling a message.
 *
 *  @version $Rev: 417 $
 */
public class ListenerPriorityBuffer implements LogEventBuffer {
    //~ Static fields/initializers -------------------------------------------------------------------------------------

    /** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(ListenerPriorityBuffer.class);

    //~ Instance fields ------------------------------------------------------------------------------------------------

    /** Buffer for messages. */
    private Buffer messageBuffer;

    /** Map between message listeners and their filters. */
    private Map<LogEventListener, List<InputFilter>> listeners;

    //~ Constructors ---------------------------------------------------------------------------------------------------

/**
     *  Creates a new ListenerPriorityBuffer object.
    */
    public ListenerPriorityBuffer() {
        messageBuffer = new UnboundedFifoBuffer();
        listeners = new HashMap<LogEventListener, List<InputFilter>>();
    }

    //~ Methods --------------------------------------------------------------------------------------------------------

    /**
     *  Adds a message to the buffer.
     *
     *  @param message message to be added.
     */
    public void receiveLogEvent(Object message) {
        messageBuffer.add(message);

        //is it good time to call this here?       
        if (listeners.size() > 0) {
            processMessage(message);
        }
    }


    /**
     *  {@inheritDoc}
     */
    public void addLogEventListener(LogEventListener listener, InputFilter filter) {
        if (listeners.containsKey(listener)) {
            //if filter is installed then just add new filter
            List<InputFilter> filters = listeners.get(listener);

            //if filters is null then create a new list first
            if (filters == null) {
                filters = new ArrayList<InputFilter>();
            }

            //and add the filter to this list
            filters.add(filter);
        } else {
            //otherwise put listener and a new list of filters into the map
            List<InputFilter> filters = new ArrayList<InputFilter>();
            filters.add(filter);
            listeners.put(listener, filters);
        }
    }


    /**
     *  {@inheritDoc}
     */
    public void addLogEventListener(LogEventListener listener) {
        if (listeners.containsKey(listener)) {
            //if listener is installed then do nothing            
        } else {
            //otherwise put the listener into the map together with null filters list
            listeners.put(listener, null);
        }
    }


    /**
     *  Processes messages.
     *
     *  @param message to be processed.
     */
    private void processMessage(Object message) {
        Set<LogEventListener> setOfListeners = listeners.keySet();

        for (LogEventListener ml : setOfListeners) {
            //get filters list
            List<InputFilter> filters = listeners.get(ml);

            //if there is at least one filter for this listener then check if it accepts the message
            if ((filters != null) && (filters.size() > 0)) {
                for (InputFilter filter : filters) {
                    //if any one of the filters accepts the message then notify listener and exit the loop
                    if (filter.accept(message)) {
                        ml.receiveLogEvent(message);

                        break;
                    }
                }
            } else {
                //otherwise, if no filter is installed then notify listener at once
                ml.receiveLogEvent(message);
            }
        }
    }
}
